﻿/**********************************************
 * 功能名称：新用户问卷
 *
 * 列表显示客户信息。约束条件为店铺。
 * 
 **************************************************************/
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using CSM.Controllers;
using CSM.Models;
using System.Text;

namespace CSM.Views.Kefu
{
    public partial class DoWJ : System.Web.UI.Page
    {
        CustomDataContext db = new CustomDataContext();
        public string alert;
       static DateTime begintime = Convert.ToDateTime("2000-1-1 0:0:0");
        static DateTime endtime = Convert.ToDateTime("2100-1-1 0:0:0");
        static Decimal MinMoney = 0;
        static Decimal MaxMoney = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var allProvince = from a in db.TCrm_Sys_Items where a.ClassID == "sf" select a;
                DropDownList_Provinces.Items.Add(new ListItem("--省份--", ""));
                foreach (var query in allProvince)
                {
                    DropDownList_Provinces.Items.Add(new ListItem(query.ItemName.Trim(), query.ItemName.Trim()));

                }
                //查询当前操作员的店铺权限及客户回访等级权限。
                string MyUserId = HttpContext.Current.Session[SystemVars.sysSessionUserId].ToString();
                var RightList = from a in db.TCsm_JS_User
                                where a.UserID == MyUserId
                                select new
                                {
                                    a.ShopRightID

                                };
                if (RightList.Count() > 0)
                {

                    string MyShopRightIdList = RightList.Single().ShopRightID;
                    if (!string.IsNullOrEmpty(MyShopRightIdList))
                    {
                        var DropList_ShopRight = MyShopRightIdList.Split(',');
                        foreach (var MyItems in DropList_ShopRight)
                        {
                            var MyShopName = (from a in db.TCrm_JC_Parameter
                                              where a.ID == Convert.ToInt32(MyItems)
                                              select a).Single();
                            ListItem InsertItem = new ListItem(MyShopName.ShopName, MyShopName.ShopID);
                            //填充店铺列表
                            DropDownList_ShopId.Items.Add(InsertItem);

                        }

                    }



                    //默认问卷信息保存到hiddenfield中。
                    var defaultStatId = (from a in db.TCrm_Sys_Items where a.ItemID == "xyhwj" select a.DefaultValue);
                    if (!string.IsNullOrEmpty(defaultStatId.Single()))
                    {
                        HiddenField_DefaultStat.Value = defaultStatId.Single().ToString();
                    }
                    else
                    {
                        Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "message", " <script>alert('新客户问卷没有定义'); </script>");
                        return;
                    }


                    //BindMyData(0);
                    //int Totals = TotalPageAmount();
                    //int pages = (Totals % 10) == 0 ? (Totals / 10) : (Totals / 10 + 1);
                    //Label_Total.Text = "共" + pages.ToString();
                    //Label_CurrenPageAndTo.Text = "页，当前第1" + " 页，转到";

                }
            }
        }
        #region 绑定数据及翻页
        private void BindMyData(int PageIndex, string starts)
        {
            if (string.IsNullOrEmpty(TextBox_Min.Text) == false)
            {
                if (PublicMethod.IsNumeric(TextBox_Min.Text) == true)
                {
                    MinMoney = Convert.ToDecimal(TextBox_Min.Text);
                }
            }
            if (string.IsNullOrEmpty(TextBox_Max.Text) == false)
            {
                if (PublicMethod.IsNumeric(TextBox_Min.Text) == true)
                {
                    MaxMoney = Convert.ToDecimal(TextBox_Max.Text);
                }
            }
            string begin = TextBox_BeginTime.Text;
            string end = TextBox_EndTime.Text;
            string Outid = TextBox_Product.Text;
            if (begin != "" || end != "")
            {
                try
                {
                    begintime = Convert.ToDateTime(begin);
                    endtime = Convert.ToDateTime(end);
                }
                catch
                {
                }
            }
            string KeySelect = DropDownList_Key.SelectedValue;
            string KeyWord = TextBox_Key.Text;
            string Provinces = DropDownList_Provinces.SelectedValue;
            var Customid = from c in db.VCrm_KF_Orders where (KeySelect == "Order" ? c.tid == KeyWord : false) select c;
            var querya = from c in db.TCrm_KF_Orders
                         where (Outid == "" ? false : c.outerid == Outid)
                         select c.buyer_nick;
            string BuyerNick = Customid.Count() == 1 ? Customid.Single().buyer_nick : "";
            string ShopId = DropDownList_ShopId.SelectedValue;
            string DefaultStatId = HiddenField_DefaultStat.Value;

            //获取新用户的无订单时间。
            var NoOrderDay = from a in db.TCrm_Sys_Items
                             where a.ItemID == "lssj"//查询参数ID“天数”
                             select a.DefaultValue;

            double Myday = 0 - Convert.ToDouble(NoOrderDay.Single());

            //获取新用户的回访金额最小值。
            var MinMoneys = from a in db.TCrm_Sys_Items
                             where a.ItemID == "je"  //查询参数ID“金额”
                             select a.DefaultValue;
          
            double MyMinMoney = 0 - Convert.ToDouble(NoOrderDay.Single());

            int skipAccount = PageIndex * 10;


            string[] state = (from a in db.TCrm_WJ_CustomerAnswer where a.StatID == DefaultStatId select a.CustomerID).Distinct().ToArray();

   
            var MyQuery = (from a in db.TCrm_KF_Customer
                           where !state.Contains(a.CustomerID)
                           && a.BlackList==false
                           && a.NoCall == false
                           && a.Num == "1"  //客户累积交易次数为1.表示新客户。
                           && a.ShopID == ShopId
                            && (KeySelect == "" ? true : (KeySelect == "Ali" ? a.AliPayID.StartsWith(KeyWord) : (KeySelect == "Phone" ? a.MobliePhone.StartsWith(KeyWord) : (KeySelect == "Receiver" ? a.ReceiverName.StartsWith(KeyWord) : (KeySelect == "Order" ? (BuyerNick == "" ? true : a.TbID.StartsWith(BuyerNick)) : true)))))
                               //&& (Receive == "" ? true : a.ReceiverName.StartsWith(Receive))
                           && (MinMoney == Convert.ToDecimal(0) ? true : a.AllMoney > MinMoney)
                           && (MaxMoney == Convert.ToDecimal(0) ? true : a.AllMoney < MaxMoney)
                               //&& (Ali == "" ? true : a.AliPayID.StartsWith(Ali))
                               //&& (BuyerNick == "" ? true : a.TbID.StartsWith(BuyerNick))
                           && (Provinces == "" ? true : a.Province.StartsWith(Provinces))
                               //&& (Phone == "" ? true : a.MobliePhone.StartsWith(Phone))
                           && (begintime == Convert.ToDateTime("2000-1-1 0:0:0") ? true : a.FinalTime > begintime)
                           && (endtime == Convert.ToDateTime("2100-1-1 0:0:0") ? true : a.FinalTime < endtime)
                           && (querya.Count() == 0 ? true : querya.Contains(a.TbID))
                           && a.FinalTime < DateTime.Now.AddDays(Myday)   //客户的最后交易时间小于 回访标准天数值。
                           select new
                           {
                               a.AllMoney,
                               a.CustomerID,
                               a.TbID,
                               a.CustomerName,
                               a.Province,
                               a.MobliePhone,
                               Address = (a.Address.Length > 20 ? a.Address.Substring(0, 20) + "..." : a.Address),
                               a.AliPayID,
                               a.Email




                           }).Skip(skipAccount).Take(10);
            GridView_Orders.DataSource = MyQuery;
            GridView_Orders.DataBind();



            if (MyQuery.Count() > 0)
            {
                Panel_Browse.Visible = true;
            }
            else
            {
                Panel_Browse.Visible = false;
                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "message", " <script>alert('没有符合条件的记录'); </script>");
            }

        }

        //查询出当前记录信息的总条数。
        private int TotalPageAmount(string starts)
        {
            int MyQuery = 0;
            string begin = TextBox_BeginTime.Text;
            string end = TextBox_EndTime.Text;
            string KeySelect = DropDownList_Key.SelectedValue;
            string KeyWord = TextBox_Key.Text;
            string ShopId = DropDownList_ShopId.SelectedValue;
            string Outid = TextBox_Product.Text;
            var Customid = from c in db.VCrm_KF_Orders where (KeySelect == "Order" ? c.tid == KeyWord : true) select c;
            var querya = from c in db.TCrm_KF_Orders
                         where (Outid == "" ? true : c.outerid == Outid)
                         select c.buyer_nick;
            string Provinces = DropDownList_Provinces.SelectedValue;
            string BuyerNick = Customid.Count() == 1 ? Customid.Single().buyer_nick : "";
            string DefaultStatId = HiddenField_DefaultStat.Value;

            //获取新用户的无订单时间。
            var NoOrderDay = from a in db.TCrm_Sys_Items
                             where a.ItemID == "lssj"//查询参数ID“天数”
                             select a.DefaultValue;

            double Myday = 0 - Convert.ToDouble(NoOrderDay.Single());

            //获取新用户的回访金额最小值。
            var MinMoneys = from a in db.TCrm_Sys_Items
                           where a.ItemID == "je"  //查询参数ID“金额”
                           select a.DefaultValue;

            double MyMinMoney = 0 - Convert.ToDouble(NoOrderDay.Single());



            string[] state = (from a in db.TCrm_WJ_CustomerAnswer where a.StatID == DefaultStatId select a.CustomerID).Distinct().ToArray();


             MyQuery = (from a in db.TCrm_KF_Customer
                           where !state.Contains(a.CustomerID)
                           && a.BlackList==false
                           && a.NoCall == false
                           && a.Num == "1"  //客户累积交易次数为1.表示新客户。
                           && a.ShopID == ShopId
                           && (KeySelect == "" ? true : (KeySelect == "Ali" ? a.AliPayID.StartsWith(KeyWord) : (KeySelect == "Phone" ? a.MobliePhone.StartsWith(KeyWord) : (KeySelect == "Receiver" ? a.ReceiverName.StartsWith(KeyWord) : (KeySelect == "Order" ? (BuyerNick == "" ? true : a.TbID.StartsWith(BuyerNick)) : true)))))
                           && (MinMoney == Convert.ToDecimal(0) ? true : a.AllMoney > MinMoney)
                           && (MaxMoney == Convert.ToDecimal(0) ? true : a.AllMoney < MaxMoney)
                           && (Provinces == "" ? true : a.Province.StartsWith(Provinces))
                           && (begintime == Convert.ToDateTime("2000-1-1 0:0:0") ? true : a.FinalTime > begintime)
                           && (endtime == Convert.ToDateTime("2100-1-1 0:0:0") ? true : a.FinalTime < endtime)
                           && (querya.Count() == 0 ? true : querya.Contains(a.TbID))
                           && a.FinalTime < DateTime.Now.AddDays(Myday)   //客户的最后交易时间小于 回访标准天数值。
                           select a).Count();
            return MyQuery;
        }


        //点击按钮，执行查询
        protected void MyClick(object sender, EventArgs e)
        {
            int pageIndx = Convert.ToInt32(CurrentPage.Value);
            string starts = txtOrder.Text;
            int Totals = TotalPageAmount(starts);
            int pages = (Totals % 10) == 0 ? (Totals / 10) : (Totals / 10 + 1);

            Label_Total.Text = "共" + pages.ToString();

            if (typeof(Button).IsInstanceOfType(sender))
            {
                string arg = ((Button)sender).CommandArgument.ToString().ToLower();

                switch (arg)
                {
                    case "first":

                        pageIndx = 0;

                        break;
                    case "gotopage":
                        if (TextBox_PageIndex.Text == "")
                        { pageIndx = 0; }
                        else
                        {
                            int xx = Convert.ToInt32(TextBox_PageIndex.Text);
                            if (xx > pages)
                            { pageIndx = pages - 1; }

                            else
                            { pageIndx = xx - 1; }


                        }
                        break;
                }

            }
            else if (typeof(LinkButton).IsInstanceOfType(sender))
            {

                string arg = ((LinkButton)sender).CommandArgument.ToString().ToLower();

                switch (arg)
                {
                    case "prev":
                        if (pageIndx > 0)
                        {
                            pageIndx = pageIndx - 1;
                        }
                        break;
                    case "next":
                        if (pageIndx < pages - 1)
                        {
                            pageIndx = pageIndx + 1;
                        }
                        break;
                    case "last":
                        pageIndx = pages - 1;
                        break;
                    case "first":
                        pageIndx = 0;
                        break;
                }

            }

            CurrentPage.Value = pageIndx.ToString();  //对保存页码状态信息的隐藏字段进行赋值。保存当前页码。
            Label_CurrenPageAndTo.Text = "页，当前第" + (pageIndx + 1).ToString() + " 页，转到";

            BindMyData(pageIndx, starts);

        }

        #endregion
        protected void Button_CallBack_Command(object sender, CommandEventArgs e)
        {
            string myCustomerId = e.CommandArgument.ToString().Trim();
            string DefaultStatId = HiddenField_DefaultStat.Value;
            var query = from a in db.TCrm_KF_Customer where a.CustomerID == myCustomerId select a;
            if (query.Single().IsLock == true)
            {
                alert = "<script>alert('该客户已被锁定，请回访下一个客户');</script>";
            }
            else
            {
                HttpContext.Current.Session[SystemVars.sysSessionCustomId] = myCustomerId;
                HttpContext.Current.Session[SystemVars.sysSessionWjType] = "xyhwj";

                Response.Redirect("../Wenjuan/html/" + DefaultStatId + ".html");
                query.Single().IsLock = true;
                db.SubmitChanges();
            }
            
        }
        protected void Button_Black_Command(object sender, CommandEventArgs e)
        {
            if (TextBox1.Value != "")
            {
                string IDList = TextBox1.Value.TrimEnd(new char[] { ',' });
                string[] CustomerId = IDList.Split(',');
                foreach (string id in CustomerId)
                {
                    var myEditQuery = (from a in db.TCrm_KF_Customer where a.CustomerID == id select a).Single();
                    myEditQuery.BlackList = true; ;
                    db.SubmitChanges();
                }
                string user = txtOrder.Text;
                BindMyData(0, user);
            }
            else
            {
                alert = "<script>alert('请先选择客户');</script>";
            }
        }
        protected void Button_NoCall_Command(object sender, CommandEventArgs e)
        {
            if (TextBox1.Value != "")
            {
                string IDList = TextBox1.Value.TrimEnd(new char[] { ',' });
                string[] CustomerId = IDList.Split(',');
                foreach (string id in CustomerId)
                {
                    var myEditQuery = (from a in db.TCrm_KF_Customer where a.CustomerID == id select a).Single();
                    myEditQuery.NoCall = true; ;
                    db.SubmitChanges();
                }
                string user = txtOrder.Text;
                BindMyData(0, user);
            }
            else
            {
                alert = "<script>alert('请先选择客户');</script>";
            }
        }

    }

}
